########################################
#### RUN THIS AFTER "build_data.R" #####
########################################




cast_fam<-data.frame(pub_debt[,2:1],debt[,1],private[,1], realestate[,1] ,total[,1])
names(cast_fam)<-c("name","pub_debt","debt","private","realestate","total")

sbjs<-data.frame(unique(sorts2$name))
names(sbjs)<-"name"
cast_fam$sbj<-ifelse(cast_fam$name %in% sbjs$name,1,0)



rows1<-seq(1,10,by=2)
rows2<-seq(2,10,by=2)


pdf("~/Dropbox/Florence_Paper/replication/figures/wealth_dist.pdf",12,12)

par(mfrow=c(2,3))
par(mar=c(2,2,2,0))


titles<-c("Tax Deductions","Debt","Private Investments","Real Estate","Total Assets")

for(i in 2:6){


plot(density(log(cast_fam[cast_fam$sbj==1,i]+1)),xlim=c(-2,14),     col=rgb(0,0,1,.5),type="n",xlab="",ylab="", main=titles[i-1]   )
polygon(density(log(cast_fam[cast_fam$sbj==1,i]+1)), col=rgb(0,0,1,.75), border= F)
polygon(density(log(cast_fam[cast_fam$sbj==0,i]+1)), col=rgb(1,0,0,.75), border= F)

if(i==2){
	
	text(2.5,.12,"Never Sorted")
	text(11.5,.15,"Sorted")
}

}

dev.off()


output_pct<-data.frame(matrix(NA,2,10))

for(i in 2:6){

cast_fam$rank_total<-rank(as.numeric(as.character(cast_fam[,i])))



cast_fam$mins<-(abs(cast_fam[,i]-median(cast_fam[cast_fam$sbj==1,i])))

output_pct[1,rows1[i-1]]<-round(min(cast_fam$rank_total[ cast_fam$mins==min(cast_fam$mins)])/nrow(cast_fam),2)

cast_fam$mins<-(abs(cast_fam[,i]-mean(cast_fam[cast_fam$sbj==1,i])))

output_pct[2,rows1[i-1]]<-round(min(cast_fam$rank_total[ cast_fam$mins==min(cast_fam$mins)])/nrow(cast_fam),2)


output_pct[,rows2[i-1]] <-"&"

if(i ==6){output_pct[,rows2[i-1]] <-"\\"}


}


names(output_pct)[rows1]<-titles
names(output_pct)[rows2]<-""

output_pct<-data.frame(cbind(c("Median","Mean"), "&"),output_pct)

names(output_pct)[c(1:2,seq(4,12,by=2))]<-""

print(output_pct)



